<?php

/**
 *  退货退款单
 */

namespace app\admin\service;

use app\admin\model\BusinessLog;
use app\admin\model\Order as ModelOrder;
use app\admin\model\ReturnorderItem;
use app\admin\model\OrderItem;
use app\admin\model\Returnorder as ModelReturnorder;
use app\admin\model\OrderPayment as ModelOrderPayment;
use app\common\service\Mail;
use app\common\exception\ThrowException;
use app\facade\Basic;
use think\facade\Db;
use app\common\service\CompleteNotificationService;
use think\facade\Log;
use app\admin\model\ReturnorderPayback as ModelReturnorderPayback;
use app\admin\model\Inventory as InventoryModel;
use app\admin\model\Images;
use app\admin\model\LogisticsOrderItem as ModelLogisticsOrderItem;

class Returnorder extends BaseService
{
    /**
     *   获取枚举
     */
    public function getEnum($param)
    {
        $modelReturnorder = new ModelReturnorder();
        $result = $modelReturnorder->getFieldEnum($param['field']);
        return Basic::data(0, 'ok', $result);
    }


    /**
     *  获取订单号
     */
    public function getOrderList($param)
    {

        $where[] = ['is_del', '=', 0];

        if (!empty($param['order_no'])) {
            $where[] = ['order_no', 'like', '%' . $param['order_no'] . '%'];
        }

        if (!empty($param['customer_id'])) {
            $where[] = ['user_id', '=', $param['customer_id']];
        }

        if (!empty($param['order_id'])) {
            $where[] = ['id', '=', $param['order_id']];
        }

        $order = ModelOrder::where($where)
            ->where('pay_status', 'in', [3, 4])
            ->where('order_type', '<>', 2)
            ->field("id,user_id,order_no,total_amount,create_time,currency")
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $param['pageSize'],
                'var_page' => 'pageIndex',
            ]);

        $order = $order->toArray();

        $order_id = array_column($order['data'], 'id');

        $all_delivery_item = ModelLogisticsOrderItem::with(['products'])
            ->alias('loi')
            ->join('logistics_order lo', 'loi.logistics_order_id = lo.id')
            ->where('loi.order_id', 'in', $order_id)
            ->where('lo.type', 1)
            ->where('lo.status', 1)
            ->field('loi.order_id,loi.product_id,SUM(loi.number) as quantity,SUM(loi.number) as max_quantity')
            ->group('loi.order_id,loi.product_id')
            ->select()
            ->toArray();

        $data = [];
        foreach ($order['data'] as $key => $value) {
            $data[$key]['id'] = $value['id'];
            $data[$key]['order_no'] = $value['order_no'];
            $data[$key]['total_amount'] = $value['total_amount'];
            $data[$key]['create_time'] = $value['create_time'];
            $data[$key]['currency'] = $value['currency'];
            $item = [];

            foreach ($all_delivery_item as $k => $v) {
                if ($v['order_id'] == $value['id']) {
                    array_push($item, $v);
                }
            }

            $data[$key]['item'] = array_values($item);
        }
        $order['data'] = $data;
        return Basic::paginator(0, 'ok', $order);
    }


    /**
     *  退货退款单列表
     */
    public function getList($param, $type = 1)
    {
        $where = [];
        /* 退货退款单编号 */
        if (!empty($param['returnorder_no'])) {
            $param['returnorder_no'] = trim($param['returnorder_no']);
            $where[] = ['returnorder_no', 'like', '%' . $param['returnorder_no'] . '%'];
        }

        /* 关联客户ID */
        if (!empty($param['customer_id'])) {
            $where[] = ['customer_id', '=', $param['customer_id']];
        }

        /* 签订人 */
        if (!empty($param['signatory'])) {
            $where[] = ['signatory', '=', $param['signatory']];
        }

        /* 退货原因 */
        if (!empty($param['return_reason'])) {
            $where[] = ['return_reason', '=', $param['return_reason']];
        }

        /* 退货退款单类型 */
        if (!empty($param['returnorder_type'])) {
            $where[] = ['returnorder_type', '=', $param['returnorder_type']];
        }

        /* 签定时间 */
        if (!empty($param['signing_start_date']) && !empty($param['signing_end_date'])) {
            $where[] = ['signing_date', 'between', [$param['signing_start_date'], $param['signing_end_date']]];
        }

        /* 退货总金额 */
        if (!empty($param['min_total_amount']) && !empty($param['max_total_amount'])) {
            $where[] = ['total_amount', 'between', [$param['min_total_amount'], $param['max_total_amount']]];
        }

        /* 已退款金额 */
        if (!empty($param['min_paid_amount']) && !empty($param['max_paid_amount'])) {
            $where[] = ['paid_amount', 'between', [$param['min_paid_amount'], $param['max_paid_amount']]];
        }

        if (2 == $type) {
            $where[] = ['status', '!=', 1];
        }

        $result = ModelReturnorder::with([
            'customerName',
            'signatory',
            'order'
        ])
            ->where($where)
            ->order('id', 'desc')
            ->field('id,returnorder_no,returnorder_type,customer_id,signatory,signing_date,total_amount,paid_amount,status,return_reason,creator,create_time,update_time,order_id')
            ->paginate([
                'list_rows' => $param['pageSize'],
                'var_page' => 'pageIndex',
            ]);

        $data = $result->toArray();

        return Basic::paginator(0, 'ok', $data);
    }

    /**
     * @describe 退款单列表
     * @author: Bobo
     * @date: 2025-08-07 16:08:03
     * @param [type] @required
     * @return Renderable
     */
    public function getRefundOrderList($param)
    {

        $where = [
            'rpb.is_del' => 0,
        ];
        if (!empty($param['status'])) {
            $where[] = ['op.status', '=', $param['status']];
        }
        if (!empty($param['transfer_type'])) {
            $where[] = ['op.transfer_type', '=', $param['transfer_type']];
        }

        $OrderPayment = new ModelOrderPayment();
        $result = $OrderPayment->alias('op')
            ->with(['user'])
            ->join('db_returnorder_payback rpb', 'rpb.payback_id = op.id')
            ->join('db_returnorder ro', 'ro.id = rpb.returnorder_id')
            ->where('ro.status', '>', 2)
            ->where($where)
            ->order('op.id', 'desc')
            ->field('ro.returnorder_no,ro.order_id,op.id,op.pay_time,op.pay_amount,op.transfer_type,op.paid_amount,op.status,op.user_id,op.create_time,ro.id as returnorder_id')
            ->paginate([
                'list_rows' => $param['pageSize'],
                'var_page' => 'pageIndex',
            ]);

        if ($result->toArray()) {
            $resultArray = $result->toArray();
            $all_order_id = array_column($resultArray['data'], 'order_id');
            $order_info = DB::name('order')->whereIn('id', $all_order_id)->field('id,order_no')->select()->toArray();
            $order_info = array_column($order_info, 'order_no', 'id');

            foreach ($resultArray['data'] as $key => &$value) {
                $value['order_no'] = $order_info[$value['order_id']] ?? '';
            }

            // 将修改后的数据重新设置回结果对象
            $result = new \think\paginator\driver\Bootstrap($resultArray['data'], $resultArray['per_page'], $resultArray['current_page'], $resultArray['total']);
        }


        return Basic::paginator(0, 'ok', $result);
    }

    /**
     * save
     */
    public function save($param)
    {
        $validate_customer_and_operator = $this->validateCustomerAndOperator($param);
        if ($validate_customer_and_operator['code'] !== 0) {
            return $validate_customer_and_operator;
        }

        $data = $param;
        $data['paid_amount'] = '0.00';
        $data['status'] = 1;
        $data['returnorder_no'] = $this->generateReturnorderNo();
        $data['create_time'] = date('Y-m-d H:i:s', time());
        $data['update_time'] = date('Y-m-d H:i:s', time());

        // 处理新增字段 - 将文件ID数组转换为逗号分隔的字符串
        if (is_array($param['attachfiles']) && !empty($param['attachfiles'])) {
            $file_ids = [];
            foreach ($param['attachfiles'] as $file) {
                if (isset($file['id'])) {
                    $file_ids[] = $file['id'];
                }
            }
            $data['attachfiles'] = implode(',', $file_ids);
        } else {
            $data['attachfiles'] = $param['attachfiles'] ?? '';
        }
        $data['payment_address'] = $param['payment_address'];

        if (!is_array($param['products_list'])) {
            return Basic::data(1, 'products_list 参数错误');
        }

        /* 合作人处理 */
        if (!empty($param['partner'])) {
            $data['partner'] = implode(',', $param['partner']);
        }

        /* 查询并验证商品明细 */
        if ($data['returnorder_type'] == 3) {
            $orderItem = $this->getAndValidateProductList($data['order_id'], $data['products_list']);
            if (isset($orderItem['code']) && $orderItem['code'] !== 0) {
                return $orderItem;
            }
        }
        $payment_list = $this->getPaymentList($data['order_id'], '00', '01');

        // 验证payment_list
        $validation_payment_result = $this->validatePaymentList($data['payment_list'], $payment_list);
        if ($validation_payment_result['code'] !== 0) {
            return $validation_payment_result;
        }

        if ($data['returnorder_type'] != 3) {
            unset($data['returnorder_method']);
            unset($data['delivery_address']);
            unset($data['tracking_number']);
            unset($data['express_company']);
        } else {
            if (1 == $data['returnorder_method']) {
                unset($data['tracking_number']);
                unset($data['express_company']);
            } else {
                unset($data['delivery_address']);
            }
        }
        $data['total_amount'] = round(array_sum(array_column($data['payment_list'], 'amount')), 2);

        Db::startTrans();
        try {
            $result = ModelReturnorder::create($data);
            Db::name('order')->where('id', $data['order_id'])->update(['aftersales_status' => 1]); // 退款审批中
            if ($data['returnorder_type'] == 3) {
                Db::name('order')->where('id', $data['order_id'])->update(['aftersales_status' => 2]); // 退货退款审批中
                $returnorder_item = [];
                foreach ($orderItem as $key => $value) {
                    $returnorder_item[$key]['returnorder_id'] = $result->id;
                    $returnorder_item[$key]['product_id'] = $value['id'];
                    // $returnorder_item[$key]['warehouse_id'] = $value['warehouse_id'];
                    $returnorder_item[$key]['return_quantity'] = $value['return_quantity'];
                    $returnorder_item[$key]['pending_qty'] = $value['return_quantity'];
                    $returnorder_item[$key]['is_futures'] = '';
                    $returnorder_item[$key]['arrival_date'] = null;
                }
                ReturnorderItem::insertAll($returnorder_item);
            }

            $returnorder_payback = [];
            foreach ($data['payment_list'] as $key => $value) {
                $returnorder_payback[$key]['returnorder_id'] = $result->id;
                $returnorder_payback[$key]['payment_id'] = $value['id'];
                $returnorder_payback[$key]['payback_id'] = $value['id'];

                $payback_id = ModelOrderPayment::insertGetId([
                    'order_id' => $param['order_id'],
                    'payment_method' => $value['payment_method'],
                    'payment_method_name' => $value['payment_method_name'],
                    'pay_type' => '02',
                    'pay_account' => $value['pay_account'],
                    'pay_amount' => $value['amount'],
                    'creator' => $data['creator'],
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'transfer_type' => $value['transfer_type'],
                    'status' => '03',
                    'notes' => $value['notes'],
                    'order_type' => $value['order_type'],
                    'order_no' => $value['order_no'],
                    'user_id' => $value['user_id'],
                    'pay_code' => $value['pay_code'],
                    'pay_currency' => $value['pay_currency'],
                    'payment_url' => $value['payment_url'],
                    'paid_amount' => 0,
                    'fee_type' => $value['fee_type'],
                ]);

                ModelReturnorderPayback::insert([
                    'returnorder_id' => $result->id,
                    'payback_id' => $payback_id,
                    'payment_id' => $value['id'],
                    'creator' => $data['creator'],
                    'create_time' => date('Y-m-d H:i:s', time()),
                ]);
            }


            // 提交事务
            Db::commit();


            // 订单发起退款通知
            try {
                $notificationService = new CompleteNotificationService();
                $notificationService->send('order_initiate_refund', $result->toArray());
            } catch (\Exception $e) {
                Log::error('退货退款单-创建 通知失败: ' . $e->getMessage() . ' 退款单编号: ' . $result->returnorder_no . ' 文件：' . $e->getFile() . ' | 行号：' . $e->getLine());
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new ThrowException(['message' => $e->getMessage()]);
        }

        /* 记录日志 */
        $this->logger->logOperation($result->id, 'returnorder', '退货退款单-创建', '退货退款单-创建', 1, 'returnorder', $result->id, '1,10');
        return Basic::data(0, '新增成功');
    }


    /**
     * 验证payment_list
     * @param array $submitted_payments 提交的payment_list
     * @param array $existing_payments 查询到的payment_list
     * @param int $id 退款单ID
     * @return array
     */
    private function validatePaymentList(&$submitted_payments, $existing_payments, $id = null)
    {
        // 将existing_payments转换为以id为key的数组，方便查找
        $existing_payments_map = array_column($existing_payments, null, 'id');

        foreach ($submitted_payments as &$payment) {
            $payment_id = $payment['id'];
            $payment_amount = $payment['amount'];

            // 第一：检查ID是否存在于existing_payments中
            if (!isset($existing_payments_map[$payment_id])) {
                return Basic::data(1, "支付记录ID {$payment_id} 不存在");
            }

            $existing_payment = $existing_payments_map[$payment_id];


            // 第二：检查amount必须小于等于paid_amount
            if ($payment_amount > $existing_payment['paid_amount']) {
                return Basic::data(1, "支付记录ID {$payment_id} 的退款金额 {$payment_amount} 不能大于已支付金额 {$existing_payment['paid_amount']}");
            }


            $payment['payment_method'] = $existing_payments_map[$payment_id]['payment_method'];
            $payment['payment_method_name'] = $existing_payments_map[$payment_id]['payment_method_name'];
            $payment['pay_account'] = $existing_payments_map[$payment_id]['pay_account'];
            $payment['order_type'] = $existing_payments_map[$payment_id]['order_type'];
            $payment['order_no'] = $existing_payments_map[$payment_id]['order_no'];
            $payment['user_id'] = $existing_payments_map[$payment_id]['user_id'];
            $payment['pay_code'] = $existing_payments_map[$payment_id]['pay_code'];
            $payment['pay_currency'] = $existing_payments_map[$payment_id]['pay_currency'];
            $payment['payment_url'] = $existing_payments_map[$payment_id]['payment_url'];
            $payment['fee_type'] = $existing_payments_map[$payment_id]['fee_type'];


            // 第二：检查is_returnorder_payment必须为0
            if ($existing_payment['is_returnorder_payment'] != 0) {
                if ($id != null && $existing_payment['returnorder_id'] == $id) {
                    continue;
                } else {
                    return Basic::data(1, "支付记录ID {$payment_id} 已被退款，不能重复退款");
                }
            }
        }

        return Basic::data(0, '验证通过');
    }

    /**
     *  获取支付记录
     */
    /**
     * @describe
     * @author: Bobo
     * @date: 2025-08-08 16:21:03
     * @param [type] $order_id
     * @param [type] $pay_type 支付类型 00 收款 02 退款
     * @param [type] $status 状态 01 已支付 03 待支付
     * @return array
     */

    public function getPaymentList($order_id, $pay_type, $status, $returnorder_id = null)
    {
        if ($returnorder_id) {
            $returnorder_payment_list = ModelReturnorderPayback::where('returnorder_id', $returnorder_id)->where('is_del', 0)->field('payback_id')->select()->toArray();
            $returnorder_payment_list = array_column($returnorder_payment_list, 'payback_id');
        } else {
            $returnorder_payment_list = [];
        }

        $payment = ModelOrderPayment::where('order_id', $order_id)
            ->where(function ($query) use ($returnorder_payment_list) {
                if ($returnorder_payment_list) {
                    $query->whereIn('id', $returnorder_payment_list);
                }
            })
            ->where('pay_type', $pay_type)
            ->whereIn('status', $status)
            ->field('id,payment_method,payment_method_name,pay_type,pay_amount,pay_account,creator,create_time,transfer_type,order_type,order_no,user_id,pay_code,pay_currency,payment_url,paid_amount,fee_type,transfer_voucher_id,status')
            ->select()
            ->toArray();
        if (!$payment) {
            return [];
        }

        $returnorder_payment_list = ModelReturnorderPayback::where('payment_id', 'in', array_column($payment, 'id'))->where('is_del', 0)->select()->toArray();
        $returnorder_payment_list = array_column($returnorder_payment_list, null, 'payment_id');


        if ('00' == $pay_type) {
            foreach ($payment as $key => &$value) {
                $value['is_returnorder_payment'] = isset($returnorder_payment_list[$value['id']]) ? 1 : 0;
                if (1 == $value['is_returnorder_payment']) {
                    $value['returnorder_id'] = $returnorder_payment_list[$value['id']]['returnorder_id'];
                }
            }
        }
        return $payment;
    }


    /**
     *  更新
     */
    public function update($param)
    {
        $result = ModelReturnorder::where('id', $param['id'])
            ->field('id,returnorder_no,returnorder_type,customer_id,signatory,signing_date,owner,total_amount,paid_amount,status,return_reason,creator,create_time,update_time')
            ->where('status', 1)
            ->find();

        if (!$result) {
            return Basic::data(1, '退货单不存在');
        }

        $validate_customer_and_operator = $this->validateCustomerAndOperator($param);
        if ($validate_customer_and_operator['code'] !== 0) {
            return $validate_customer_and_operator;
        }


        /* 查询并验证商品明细 */
        if ($param['returnorder_type'] == 3) {
            $orderItem = $this->getAndValidateProductList($param['order_id'], $param['products_list']);
            if (isset($orderItem['code']) && $orderItem['code'] !== 0) {
                return $orderItem;
            }
        }


        $payment_list = $this->getPaymentList($param['order_id'], '00', '01');

        // 验证payment_list
        $validation_payment_result = $this->validatePaymentList($param['payment_list'], $payment_list, $param['id']);
        if ($validation_payment_result['code'] !== 0) {
            return $validation_payment_result;
        }

        if ($param['returnorder_type'] != 3) {
            unset($param['returnorder_method']);
            unset($param['delivery_address']);
            unset($param['tracking_number']);
            unset($param['express_company']);
        } else {
            if (1 == $param['returnorder_method']) {
                unset($param['tracking_number']);
                unset($param['express_company']);
            } else {
                unset($param['delivery_address']);
            }
        }


        $result->returnorder_type = $param['returnorder_type'];
        $result->signatory = $param['signatory'];
        $result->signing_date = $param['signing_date'];
        $result->owner = $param['owner'];
        /* 合作人处理 */
        if (!empty($param['partner'])) {
            $result->partner = implode(',', $param['partner']);
        }
        $result->total_amount = round(array_sum(array_column($param['payment_list'], 'amount')), 2);
        $result->return_reason = $param['return_reason'];
        $result->remark = $param['remark'];
        $result->update_time = date('Y-m-d H:i:s', time());

        // 处理新增字段 - 将文件ID数组转换为逗号分隔的字符串
        if (is_array($param['attachfiles']) && !empty($param['attachfiles'])) {
            $file_ids = [];
            foreach ($param['attachfiles'] as $file) {
                if (isset($file['id'])) {
                    $file_ids[] = $file['id'];
                }
            }
            $result->attachfiles = implode(',', $file_ids);
        } else {
            $result->attachfiles = $param['attachfiles'] ?? '';
        }
        $result->payment_address = $param['payment_address'];


        Db::startTrans();
        try {

            /* 更新退款单主表 */
            if (!$result->save()) {
                throw new ThrowException(['message' => '更新退款单主表失败']);
            }

            ReturnorderItem::where('returnorder_id', $result->id)->delete();

            if ($param['returnorder_type'] == 3) {
                /* 删除明细 */
                $returnorder_item = [];
                foreach ($orderItem as $key => $value) {
                    $returnorder_item[$key]['returnorder_id'] = $result->id;
                    $returnorder_item[$key]['product_id'] = $value['id'];
                    // $returnorder_item[$key]['warehouse_id'] = $value['warehouse_id'];
                    $returnorder_item[$key]['return_quantity'] = $value['return_quantity'];
                    $returnorder_item[$key]['pending_qty'] = $value['return_quantity'];
                    $returnorder_item[$key]['is_futures'] = '';
                    $returnorder_item[$key]['arrival_date'] = null;
                }
                ReturnorderItem::insertAll($returnorder_item);
            }


            /* 更新支付记录 */

            $returnorder_payback = [];
            $all_payment_id = array_column($param['payment_list'], 'id');

            $old_payment_list = ModelReturnorderPayback::where('returnorder_id', $result->id)
                ->where('payment_id', 'in', $all_payment_id)
                ->where('is_del', 0)
                ->select()
                ->toArray();

            $old_payback_id = array_column($old_payment_list, 'payback_id');

            ModelOrderPayment::where('id', 'in', $old_payback_id)->delete();
            ModelReturnorderPayback::where('returnorder_id', $result->id)->where('is_del', 0)->delete();

            foreach ($param['payment_list'] as $key => $value) {
                $returnorder_payback[$key]['returnorder_id'] = $result->id;
                $returnorder_payback[$key]['payment_id'] = $value['id'];
                $returnorder_payback[$key]['payback_id'] = $value['id'];

                $payback_id = ModelOrderPayment::insertGetId([
                    'order_id' => $param['order_id'],
                    'payment_method' => $value['payment_method'],
                    'payment_method_name' => $value['payment_method_name'],
                    'pay_type' => '02',
                    'pay_account' => $value['pay_account'],
                    'pay_time' => date('Y-m-d H:i:s', time()),
                    'pay_amount' => $value['amount'],
                    'creator' => $param['creator'],
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'transfer_type' => $value['transfer_type'],
                    'status' => '03',
                    'notes' => $value['notes'],
                    'order_type' => $value['order_type'],
                    'order_no' => $value['order_no'],
                    'user_id' => $value['user_id'],
                    'pay_code' => $value['pay_code'],
                    'pay_currency' => $value['pay_currency'],
                    'payment_url' => $value['payment_url'],
                    'paid_amount' => 0,
                    'fee_type' => $value['fee_type'],
                ]);

                ModelReturnorderPayback::insert([
                    'returnorder_id' => $result->id,
                    'payback_id' => $payback_id,
                    'payment_id' => $value['id'],
                    'creator' => $param['creator'],
                    'create_time' => date('Y-m-d H:i:s', time()),
                ]);
            }

            Db::commit();


            // 订单发起退款通知
            try {
                $notificationService = new CompleteNotificationService();
                $notificationService->send('order_initiate_refund', $result->toArray());
            } catch (\Exception $e) {
                Log::error('退货退款单-编辑: ' . $e->getMessage() . ' 退款单编号: ' . $result->returnorder_no . ' 文件：' . $e->getFile() . ' | 行号：' . $e->getLine());
            }
        } catch (\Exception $e) {
            Db::rollback();
            throw new ThrowException(['message' => $e->getMessage()]);
        }

        /* 记录日志 */
        $this->logger->logOperation($result->id, 'returnorder', '退货退款单-编辑', '退货退款单-编辑');
        return Basic::data(0, '更新成功');
    }

    /**
     *  获取详情
     */
    public function detail($param)
    {


        $operatorService = new Operator();
        $operator = $operatorService->getOperatorName();

        $result = ModelReturnorder::with([
            'creator_name' => function ($query) {
                return $query->field('id,cname');
            },
            'customerName' => function ($query) {
                return $query->field('id,cusname');
            },
            'products_list' => function ($query) {
                return $query->with([
                    'product' => function ($query) {
                        $query->field('id,cname');
                    },
                    'warehouses' => function ($query) {
                        $query->field('id,name');
                    }
                ])->field('id,returnorder_id,product_id,warehouse_id,is_futures,arrival_date,return_quantity,pending_qty');
            }
        ])
            ->where('id', '=', $param['id'])
            ->field('id,returnorder_no,returnorder_type,returnorder_method,delivery_address,tracking_number,express_company,customer_id,order_id,signatory,signing_date,owner,partner,total_amount,paid_amount,status,return_reason,remark,creator,create_time,update_time,attachfiles,payment_address')
            ->find();
        if (!$result) {
            return Basic::data(1, '未找到');
        }

        $data = $result->toArray();


        if (!empty($data['partner'])) {
            $data['partner'] = array_map(function ($item) {
                return (int) $item;
            }, explode(',', $data['partner']));

            $partner_str = '';
            foreach ($data['partner'] as $key => $value) {
                if (isset($operator[$value])) {
                    $partner_str .= $operator[$value] . ',';
                }
            }
            $data['partner_value'] = rtrim($partner_str, ',');
        } else {
            $data['partner'] = [];
            $data['partner_list'] = '';
        }

        /* 创建人 */
        if (isset($data['creator_name'])) {
            $data['creator_name'] = $data['creator_name']['cname'];
        } else {
            $data['creator_name'] = '';
        }




        /* 查询订单 */
        $data['order_item_list'] = $this->getMergedOrderItem($data);
        $orderInfo = $this->getOrderInfo($data);
        $data['order_no'] = $orderInfo->order_no;
        $data['currency'] = $orderInfo->currency;

        $products_list = [];
        if (isset($data['products_list'])) {
            foreach ($data['products_list'] as $key => $value) {

                $products_list[$key]['id'] = $value['id'];
                $products_list[$key]['product_id'] = $value['product_id'];
                $products_list[$key]['return_quantity'] = $value['return_quantity'];
                $products_list[$key]['pending_qty'] = $value['pending_qty'];

                /* 商品名称 */
                if (isset($value['product'])) {
                    $products_list[$key]['product_name'] = $value['product']['cname'];
                } else {
                    $products_list[$key]['product_name'] = '';
                }

                /* 仓库名称 */
                if (isset($value['warehouses'])) {
                    $products_list[$key]['warehouses_name'] = $value['warehouses']['name'];
                    $products_list[$key]['warehouses_id'] = $value['warehouses']['id'];
                } else {
                    $products_list[$key]['warehouses_name'] = '';
                }
            }
        }
        $data['products_list'] = $products_list;

        /* 支付列表 */
        $data['payment_list'] = $this->getPaymentList($result['order_id'], '02', ['01', '03'], $result['id']);


        $all_voucher_id = array_column($data['payment_list'], 'transfer_voucher_id');
        $all_voucher_id = array_unique(array_map('intval', explode(',', implode(',', $all_voucher_id))));
        $oImages = new Images();
        $imgObject = [];
        if (count($all_voucher_id) > 0) {
            $imgObject = $oImages->getImagesByIds($all_voucher_id);
            $imgObject = array_column($imgObject, null, 'id');
        }


        $payback_id = array_column($data['payment_list'], 'id');

        $returnorder_payback_list = ModelReturnorderPayback::where('returnorder_id', $result['id'])->where('payback_id', 'in', $payback_id)->select()->toArray();

        $returnorder_payback_list = array_column($returnorder_payback_list, null, 'payback_id');

        foreach ($data['payment_list'] as $key => &$value) {
            $value['payment_id'] = isset($returnorder_payback_list[$value['id']]) ? $returnorder_payback_list[$value['id']]['payment_id'] : 0;

            // 处理 transfer_voucher_id 可能是逗号分隔字符串的情况
            if ($value['transfer_voucher_id']) {
                $voucher_ids = explode(',', $value['transfer_voucher_id']);
                $voucher_urls = [];
                foreach ($voucher_ids as $voucher_id) {
                    if (isset($imgObject[$voucher_id])) {
                        $voucher_urls[] = $imgObject[$voucher_id];
                    }
                }
                $value['transfer_voucher_url'] = $voucher_urls;
            } else {
                $value['transfer_voucher_url'] = [];
            }
        } // 获取退款单相关的支付单

        /* 日志 */
        $data['business_list'] = $this->getBusinessList($result);

        // 处理附件字段格式转换 - 获取完整的文件信息
        if (!empty($data['attachfiles'])) {
            $attachfiles_ids = explode(',', $data['attachfiles']);
            $oImages = new Images();
            $attachfiles_data = $oImages->getImagesByIds($attachfiles_ids);
            $data['attachfiles'] = $attachfiles_data ?: [];
        } else {
            $data['attachfiles'] = [];
        }

        if ($result) {
            return Basic::data(0, 'ok', $data);
        } else {
            return Basic::data(1, '获取失败');
        }
    }

    /**
     *  获取日志记录
     */
    public function getBusinessList($result)
    {
        $where['business_module'] = 'returnorder';
        $where['entity_id'] = $result->id;
        $result = BusinessLog::with(['operator' => function ($query) {
            $query->field('id,cname');
        }])->where($where)->field('id,user_id,operate,ip_address,content,create_time')->select();

        foreach ($result as $key => &$value) {
            if (isset($value->operator)) {
                $value->operator_name = $value->operator->cname;
                unset($value->operator);
            } else {
                $value->operator_name = '';
            }
        }

        if ($result) {
            return $result->toArray();
        } else {
            return [];
        }
    }



    /**
     *  上传支付凭证
     */
    public function returnorderPayment($param)
    {
        $returnorder_payback = ModelReturnorderPayback::alias('rpb')
            ->join('db_returnorder ro', 'ro.id = rpb.returnorder_id')
            ->join('db_order_payment op', 'op.id = rpb.payback_id')
            ->where('rpb.payback_id', $param['id'])
            ->field('rpb.id,rpb.returnorder_id,rpb.payment_id,rpb.payback_id,op.pay_amount,ro.status,ro.paid_amount,ro.total_amount,ro.returnorder_no,ro.customer_id,ro.order_id,ro.partner,ro.owner')
            ->find()
            ->toArray();

        if (!$returnorder_payback) {
            return Basic::data(1, 'ID 错误，未找到退款单');
        }

        /* 判断退款金额 */
        if ($param['amount'] >  $returnorder_payback['pay_amount']) {
            return Basic::data(1, '退款金额大于退款单金额');
        }

        if ($returnorder_payback['status'] != 3) {
            return Basic::data(1, '退货退款单状态错误，无法退款');
        }


        $orderInfo = ModelOrder::where('id', $returnorder_payback['order_id'])->field('id,order_no,currency,user_id')->find()->toArray();
        $returnorderInfo = ModelReturnorder::where('id', $returnorder_payback['returnorder_id'])->field('id,returnorder_no,paid_amount,returnorder_type')->find()->toArray();


        Db::startTrans();
        try {

            Db::name('order_payment')
                ->where('id', $returnorder_payback['payback_id'])
                ->update([
                    'paid_amount' => $param['amount'],
                    'status' => '01',
                    'transfer_voucher_id' => $param['voucher_id'],
                    'notes' => $param['notes']
                ]);

            $returnorder_update = [
                'paid_amount' => $returnorder_payback['paid_amount'] + $param['amount'],
                'update_time' => date('Y-m-d H:i:s', time()),
                'status' => 5
            ];

            $returnorder_payback_status = DB::name('returnorder_payback')
                ->alias('rpb')
                ->join('db_order_payment op', 'op.id = rpb.payback_id')
                ->field('op.status')
                ->where('rpb.returnorder_id', $returnorder_payback['returnorder_id'])
                ->where('rpb.is_del', 0)
                ->group('op.status')
                ->select()
                ->toArray(); // 退款单关联的退货退款单状态
            $returnorder_payback_status = array_column($returnorder_payback_status, 'status');
            if (1 == count($returnorder_payback_status) && in_array('01', $returnorder_payback_status)) { // 退款单关联的退货退款单全部退款成功
                Db::name('returnorder')
                    ->where('id', $returnorder_payback['returnorder_id'])
                    ->update($returnorder_update);
                if ($returnorderInfo['returnorder_type'] == 3) {
                    Db::name('order')->where('id', $orderInfo['id'])->update(['aftersales_status' => 32]); // 已退货 已退款
                } else {
                    Db::name('order')->where('id', $orderInfo['id'])->update(['aftersales_status' => 16]); // 已退款
                }
            }

            Db::commit();
            $mailService = new Mail();
            $data = [
                'orderInfo' => [
                    'orderNo' => $orderInfo['order_no'],
                    'user_id' => $returnorder_payback['customer_id'],
                    'lang' => 'en'
                ],
                'returnorderInfo' => [
                    'returnorder_no' => $returnorder_payback['returnorder_no'],
                    'returnorder_paid_amount' => $returnorder_payback['paid_amount'],
                ],
            ];
            $mailService->send('order_refund',  $data);

            // 订单退款通过通知
            try {
                $order = ModelOrder::where('id', $returnorder_payback['order_id'])->find();
                $orderPartner = $order->partner ? array_filter(explode(',', $order->partner)) : [];
                $customer = Db::name('customer')->where('id', $order->user_id)->find();
                $customerPartner = $customer['partner'] ? array_filter(explode(',', $customer['partner'])) : [];
                $resultPartnerArr = $returnorder_payback['partner'] ? array_filter(explode(',', $returnorder_payback['partner'])) : [];
                $recipients = array_filter(array_unique([$order->owner, $order->signatory, $customer['owner'], $returnorder_payback['owner'], ...$orderPartner, ...$customerPartner, ...$resultPartnerArr]));

                $notificationService = new CompleteNotificationService();
                $notificationService->send('order_refund_approved', $returnorder_payback, $recipients);
            } catch (\Exception $e) {
                Log::error('订单退款通过通知失败: ' . $e->getMessage() . ' 退款单编号: ' . $returnorder_payback['returnorder_no'] . ' 文件：' . $e->getFile() . ' | 行号：' . $e->getLine());
            }
        } catch (\Exception $e) {
            Db::rollback();
            throw new ThrowException(['message' => $e->getMessage()]);
        }

        /* 记录日志 */
        $this->logger->logOperation($returnorder_payback['returnorder_id'], 'returnorder', '退货退款单-退款单上传退款凭证', '退款单金额：' . $param['amount']);
        return Basic::data(0, '操作成功');
    }


    /**
     *  取消退款单
     */
    public function cancel($param)
    {

        $returnorder = ModelReturnorder::where('id', $param['id'])->where('creator', $param['creator'])
            ->field('id,status,order_id')

            ->find();

        if (!$returnorder) {
            return Basic::data(1, 'ID 错误，未找到退货退款单');
        }

        if ($returnorder->status != 1) {
            return Basic::data(1, '退货退款单状态错误，无法取消');
        }

        Db::startTrans();
        try {

            $returnorder->status = 4;
            $returnorder->update_time = date('Y-m-d H:i:s', time());

            if (!$returnorder->save()) {
                throw new ThrowException(['message' => '更新退款单错误']);
            }
            $returnorderPayback = ModelReturnorderPayback::where('returnorder_id', $returnorder->id)->field('id,returnorder_id,payment_id,payback_id')->select()->toArray();
            if (!empty($returnorderPayback)) {
                $payback_id = array_column($returnorderPayback, 'payback_id');
                ModelOrderPayment::whereIn('id', $payback_id)->delete();
                ModelReturnorderPayback::where('returnorder_id', $returnorder->id)->update(['is_del' => time()]);
            }
            Db::name('order')->where('id', $returnorder->order_id)->update(['aftersales_status' => null]); // 订单售后状态null
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            throw new ThrowException(['message' => $th->getMessage()]);
        }
        /* 记录日志 */
        $this->logger->logOperation($returnorder->id, 'returnorder', '退货退款单-撤销', '退货退款单-撤销');
        return Basic::data(0, '操作成功');
    }


    /**
     *  退款单审核
     */
    public function review($param)
    {
        $returnorder = ModelReturnorder::where('id', $param['id'])
            ->field('id,status,returnorder_type,returnorder_no,order_id')
            ->find();

        if (!$returnorder) {
            return Basic::data(1, 'ID 错误，未找到退款单');
        }

        if ($returnorder->status > 1) {
            return Basic::data(1, '退货退款单状态错误，无法审核');
        }

        $returnorder->reviewer = $param['creator'];
        $returnorder->reviewer_time = date('Y-m-d H:i:s', time());
        $returnorder->update_time = date('Y-m-d H:i:s', time());


        if ($param['status'] == 1) {

            Db::startTrans();
            try {
                if ($returnorder->returnorder_type == 3) { // 退款且退货
                    $returnorder->status = 2;
                    if (!$returnorder->save()) {
                        return Basic::data(1, '退款单审核失败');
                    }

                    Db::name('order')->where('id', $returnorder->order_id)->update(['aftersales_status' => 3]);

                    // 退货退款单审核通过通知
                    try {
                        $notificationService = new CompleteNotificationService();
                        $notificationService->send('return_order_stock', $returnorder->toArray());
                    } catch (\Exception $e) {
                        Log::error('退货退款单审核通过通知失败: ' . $e->getMessage() . ' 退款单编号: ' . $returnorder->returnorder_no . ' 文件：' . $e->getFile() . ' | 行号：' . $e->getLine());
                    }
                } else {
                    $returnorder->status = 3;
                    if (!$returnorder->save()) {
                        return Basic::data(1, '退款单审核失败');
                    }

                    Db::name('order')->where('id', $returnorder->order_id)->update(['aftersales_status' => 8]);
                    $this->sendReturnOrderRefundNotification($returnorder);
                }
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                throw new ThrowException(['message' => $th->getMessage()]);
            }
            /* 记录日志 */
            $this->logger->logOperation($returnorder->id, 'returnorder', '退货退款单-审核通过', '退货退款单-审核通过');
        } else {
            Db::startTrans();
            try {

                $returnorder->status = 4;
                $returnorder->update_time = date('Y-m-d H:i:s', time());

                if (!$returnorder->save()) {
                    throw new ThrowException(['message' => '更新退款单错误']);
                }
                $returnorderPayback = ModelReturnorderPayback::where('returnorder_id', $returnorder->id)->field('id,returnorder_id,payment_id,payback_id')->select()->toArray();
                if (!empty($returnorderPayback)) {
                    $payback_id = array_column($returnorderPayback, 'payback_id');
                    ModelOrderPayment::whereIn('id', $payback_id)->delete();
                    ModelReturnorderPayback::where('returnorder_id', $returnorder->id)->update(['is_del' => time()]);
                }
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                throw new ThrowException(['message' => $th->getMessage()]);
            }
            /* 记录日志 */
            $this->logger->logOperation($returnorder->id, 'returnorder', '退货退款单-审核驳回', '退货退款单-审核驳回');
        }
        $approverWhere = [
            'entity_id' => $returnorder->id,
            'business_module' => 'returnorder',
            'operate' => '退货退款单-创建',

        ];
        $this->logger->updateApprover($approverWhere, $param['creator']);

        return Basic::data(0, '操作成功');
    }

    /**
     *  生成 订单号
     */
    public function generateReturnorderNo()
    {
        $startTime = date('Y-m-d') . ' 00:00:00';
        $endTime = date('Y-m-d') . ' 23:59:59';
        $where[] = ['create_time', 'between', [$startTime, $endTime]];
        $count = ModelReturnorder::where($where)->field('id')->count();
        return 'TK.' . date('Ymd') . str_pad(($count + 1), 4, "0", STR_PAD_LEFT);
    }



    /**
     * @describe 查询订单产品列表，并验证产品列表
     * @author: Bobo
     * @date: 2025-08-07 14:12:28
     * @param [type] @required
     * @return Renderable
     */
    public function getAndValidateProductList($order_id, $product)
    {
        $productItem = ModelLogisticsOrderItem::with(['products'])
            ->alias('loi')
            ->join('logistics_order lo', 'loi.logistics_order_id = lo.id')
            ->where('loi.order_id', 'in', $order_id)
            ->where('lo.type', 1)
            ->where('lo.status', 1)
            ->field('loi.order_id,loi.product_id,SUM(loi.number) as number')
            ->group('loi.order_id,loi.product_id')
            ->select()
            ->toArray();

        $productItem = array_column($productItem, null, 'product_id');


        if (!$productItem) {
            return [];
        }
        $productItem = array_column($productItem, null, 'product_id');

        foreach ($product as $key => &$value) {
            if (!isset($productItem[$value['id']])) {
                return Basic::data(1, '商品不存在');
            }

            if ($value['return_quantity'] > $productItem[$value['id']]['number']) {
                return Basic::data(1, '退货商品商品数量超过发货数量，请重新选择');
            }
            // $value['warehouse_id'] = $productItem[$value['id']]['warehouse_id'];
        }

        return $product;
    }

    /**
     *  编辑使用
     */

    public function getMergedOrderItem($data)
    {
        $orderItem = ModelLogisticsOrderItem::with(['products'])
            ->alias('loi')
            ->join('logistics_order lo', 'loi.logistics_order_id = lo.id')
            ->where('loi.order_id', 'in', $data['order_id'])
            ->where('lo.type', 1)
            ->where('lo.status', 1)
            ->field('loi.order_id,loi.product_id,SUM(loi.number) as quantity')
            ->group('loi.order_id,loi.product_id')
            ->select()
            ->toArray();
        if (!$orderItem) {
            return [];
        }

        $products_list = array_column($data['products_list'], null, 'product_id');

        foreach ($orderItem as $orderItemKey => &$value) {

            if (!isset($products_list[$value['product_id']])) {
                $value['selected'] = 0;
                $value['return_quantity'] =  $value['quantity'];
            } else {
                $value['return_quantity'] = $products_list[$value['product_id']]['return_quantity'];
                $value['product_name'] = $products_list[$value['product_id']]['product']['cname'];
                $value['selected'] = 1;
            }
        }
        $orderItem = array_values($orderItem);
        return $orderItem;
    }


    /**
     *  获取订单单号
     */
    public function getOrderInfo($data)
    {
        return  ModelOrder::where('id', $data['order_id'])->field('order_no,currency')->find();
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-08-08 13:18:39
     * @param [type] @required
     * @return Renderable
     */
    public function stock($param)
    {
        $returnorder = ModelReturnorder::where('id', $param['id'])->with(['products_list'])->find();
        if (!$returnorder) {
            return Basic::data(1, 'ID 错误，未找到退货退款单');
        }

        if ($returnorder->status != 2) {
            return Basic::data(1, '退货退款单状态错误，无法退货入库');
        }

        if ($returnorder->returnorder_type != 3) {
            return Basic::data(1, '退货退款单类型错误，无法退货入库');
        }


        $pedding_stock_list = array_column($returnorder->products_list->toArray(), null, 'product_id');

        $stock_list = [];

        foreach ($param['stock_list'] as $key => $value) {
            if (!isset($value['product_id']) || $value['product_id'] < 1) {
                return Basic::data(1, '商品ID不存在');
            }

            if (!isset($value['number']) || $value['number'] < 1) {
                return Basic::data(1, '商品数量不存在');
            }

            if (!isset($value['wid']) || $value['wid'] < 1) {
                return Basic::data(1, '仓库ID不存在');
            }

            if (!isset($value['type']) || $value['type'] < 1 || $value['type'] > 2) {
                return Basic::data(1, '类型错误');
            }

            if (isset($value['remark']) && mb_strlen($value['remark']) > 255) {
                return Basic::data(1, '备注长度超过255个字符');
            }

            if (isset($stock_list[$value['product_id']])) {
                $stock_list[$value['product_id']]['number'] += $value['number'];
            } else {
                $stock_list[$value['product_id']] = $value;
            }
        }


        foreach ($stock_list as $key => $value) {

            if (!isset($pedding_stock_list[$value['product_id']])) {
                return Basic::data(1, '商品不存在');
            }

            if ($value['number'] > $pedding_stock_list[$value['product_id']]['pending_qty']) {
                return Basic::data(1, '入库商品商品数量超过发货数量，请重新选择');
            }
        }


        Db::startTrans();
        try {


            $damage_stock = []; // 报损入库
            foreach ($param['stock_list'] as $key => $value) {
                if (isset($pedding_stock_list[$value['product_id']])) {
                    $pedding_stock_list[$value['product_id']]['pending_qty'] -= $value['number'];

                    Db::name('returnorder_item')
                        ->where('returnorder_id', $param['id'])
                        ->where('product_id', $value['product_id'])
                        ->dec('pending_qty', $value['number'])
                        ->update();
                }
                if ($value['type'] == 1) { // 正常入库

                    $inventory = InventoryModel::where('productid', $value['product_id'])
                        ->with(['product_prices' => function ($query) {
                            $query->where('is_del', 0);
                        }])
                        ->where('wid', $value['wid'])
                        ->where('is_futures', 0)
                        ->where('is_del', 0)
                        ->order('id', 'desc')
                        ->select()
                        ->toArray();


                    $productPrice = [];
                    foreach ($inventory as $key => $inventory_value) {
                        if (isset($inventory_value['product_prices']) && !empty($inventory_value['product_prices'])) {
                            $productPrice = $inventory_value['product_prices'];
                            break;
                        }
                    }

                    $fl_warehouse_id = Db::name('warehouse')->where('id', $value['wid'])->field('id,fl_warehouse_id')->find();
                    $cc_name_id = Db::name('cc_names')
                        ->whereRaw('find_in_set(?,sellable_wids)', [$fl_warehouse_id['fl_warehouse_id']])
                        ->where('is_del', 0)
                        ->select()
                        ->toArray();
                    $cc_name_id = array_column($cc_name_id, 'id');
                    $cc_name_id = implode(',', $cc_name_id);

                    $inventory_id = Db::name('inventory')->insertGetId([
                        'productid' => $value['product_id'],
                        'wid' => $value['wid'],
                        'source_table' => 'returnorder',
                        'source_id' => $param['id'],
                        'initial_qty' => $value['number'],
                        'available_qty' => $value['number'],
                        'is_sale' =>  count($productPrice) > 0 ? 1 : 0,
                        'is_futures' => 0,
                        'remark' => $value['remark'],
                        'creator' => $param['creator'],
                        'create_time' => date('Y-m-d H:i:s', time()),
                        'is_del' => 0,
                        'ccname_ids' => $cc_name_id ?? ''
                    ]); // 入库

                    if (count($productPrice) > 0 && $inventory_id > 0) { // 商品价格
                        foreach ($productPrice as $key => $price_value) {
                            $product_price_id = Db::name('product_price')->insertGetId([
                                'inventory_id' => $inventory_id,
                                'wid' => $price_value['wid'],
                                'transaction_currency_id' => $price_value['transaction_currency_id'],
                                'price' => $price_value['price'],
                                'remark' => $price_value['remark'],
                                'first_leg_logistics_fee' => $price_value['first_leg_logistics_fee'],
                                'creator' => $param['creator'],
                                'create_time' => date('Y-m-d H:i:s', time()),
                                'is_del' => 0,
                            ]);
                            if (isset($price_value['discount']) && !empty($price_value['discount'])) {
                                foreach ($price_value['discount'] as $key => $discount_value) {
                                    Db::name('product_discount')->insert([
                                        'level' => $discount_value['level'],
                                        'num' => $discount_value['num'],
                                        'price' => $discount_value['price'],
                                        'price_id' => $product_price_id,
                                        'creator' => $param['creator'],
                                        'create_time' => date('Y-m-d H:i:s', time())
                                    ]);
                                }
                            }
                        }
                    }
                } else {
                    $damage_stock[] = [
                        'returnorder_id' => $param['id'],
                        'product_id' => $value['product_id'],
                        'wid' => $value['wid'],
                        'quantity' => $value['number'],
                        'remark' => $value['remark'],
                        'creator' => $param['creator'],
                        'create_time' => date('Y-m-d H:i:s', time()),
                        'is_del' => 0,
                    ];
                }
            }


            if (!empty($damage_stock)) {
                Db::name('product_damage_report')->insertAll($damage_stock);
            }

            $isAllStock = true;
            foreach ($pedding_stock_list as $key => $value) {
                if ($value['pending_qty'] > 0) {
                    $isAllStock = false;
                    break;
                }
            }
            if ($isAllStock) { // 退货单全部入库
                $returnorder->status = 3;
                $returnorder->update_time = date('Y-m-d H:i:s', time());
                $returnorder->save();
                Db::name('order')->where('id', $returnorder->order_id)->update(['aftersales_status' => 4]);
            }

            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            throw new ThrowException(['message' => $th->getMessage()]);
        }

        if ($returnorder->status == 3) {
            $this->sendReturnOrderRefundNotification($returnorder);
        }
        /* 记录日志 */
        $this->logger->logOperation($returnorder->id, 'returnorder', '退货退款单-退货单入库', '退货退款单-退货单入库');
        return Basic::data(0, '操作成功');
    }

    /**
     * @describe  财务退款通知
     * @author: Bobo
     * @date: 2025-08-08 14:18:08
     * @param [type] @required
     * @return Renderable
     */
    public function sendReturnOrderRefundNotification($returnorder)
    {
        $returnorderPayback = ModelReturnorderPayback::where('returnorder_id', $returnorder->id)->field('id,returnorder_id,payment_id,payback_id')->select()->toArray();
        $payback_ids = array_column($returnorderPayback, 'payback_id');
        $payback_list = ModelOrderPayment::whereIn('id', $payback_ids)->field('id,transfer_type')->select()->toArray();

        foreach ($payback_list as $key => $value) {
            // 全部入库待退款通知
            try {
                $notificationService = new CompleteNotificationService();
                $notificationService->send('return_order_refund', $value);
            } catch (\Exception $e) {
                Log::error('退货退款单审核通过通知失败: ' . $e->getMessage() . ' 退款单编号: ' . $returnorder->returnorder_no . ' 文件：' . $e->getFile() . ' | 行号：' . $e->getLine());
            }
        }
    }

    /**
     * @describe 验证客户和操作员
     * @author: Bobo
     * @date: 2025-08-08 11:15:45
     * @param [type] @required
     * @return Renderable
     */
    private function validateCustomerAndOperator($param)
    {
        if (isset($param['customer_id'])) {
            $customer = ModelReturnorder::name('customer')->where('id', $param['customer_id'])->where('is_del', 0)->find();
            if (!$customer) {
                return Basic::data(1, '客户不存在');
            }
        } else {
            return Basic::data(0, '客户不存在');
        }
        if (isset($param['signatory'])) {
            $operator = ModelReturnorder::name('operator')->where('id', $param['signatory'])->where('is_del', 0)->find();
            if (!$operator) {
                return Basic::data(1, '签订人不存在');
            }
        } else {
            return Basic::data(0, '签订人不存在');
        }

        if (isset($param['owner'])) {
            $owner = ModelReturnorder::name('operator')->where('id', $param['owner'])->where('is_del', 0)->find();
            if (!$owner) {
                return Basic::data(1, '负责人不存在');
            }
        } else {
            return Basic::data(0, '负责人不存在');
        }

        if (isset($param['partner']) && !empty($param['partner'])) {
            $partner = ModelReturnorder::name('operator')->whereIn('id', $param['partner'])->where('is_del', 0)->select()->toArray();
            if (!$partner) {
                return Basic::data(1, '合作人不存在');
            }
            if (count($partner) != count($param['partner'])) {
                return Basic::data(1, '合作人不存在');
            }
        } else {
            return Basic::data(0, '合作人不存在');
        }

        return Basic::data(0, '操作成功');
    }

    /**
     * 获取操作记录
     * @describe
     * @author: Assistant
     * @date: 2025-01-27 10:00:00
     * @param int $page 页码
     * @param int $limit 每页数量
     * @param int $returnorderId 退货退款单ID
     * @param string $field 查询字段
     * @return array
     */
    public function getOperationRecords(int $page = 1, int $limit = 10, $returnorderId = 0, $field = "*")
    {
        $businessLogModel = new \app\admin\model\BusinessLog();
        $query = $businessLogModel
            ->with(['operator' => function ($query) {
                $query->bind(['user_name' => 'cname'])
                    ->field(['id', 'cname as user_name']);
            }])
            ->where('business_module', 'returnorder');

        if (!empty($returnorderId)) {
            $query->where('entity_id', $returnorderId);
        }

        $total = $query->count();
        $list = $query
            ->field($field)
            ->page($page, $limit)
            ->order('id desc')
            ->select()
            ->each(function ($item) {
                if (isset($item['operator']['user_name'])) {
                    $item['user_name'] = $item['operator']['user_name'];
                    unset($item['operator']);
                } elseif ($item['user_type'] == 2) {
                    $item['user_name'] = '客户自己';
                }
                return $item;
            })
            ->toArray();

        return ['code' => 0, 'message' => 'success', 'data' => ['list' => $list, 'total' => $total]];
    }
}
